package tests;

import static org.junit.Assert.*;

import java.util.List;
import java.util.Properties;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import ownserver.ServerShip;
import pathfinding.DStarGridDiagSimpleTabled;
import pathfinding.GridCell;
import pathfinding.SpaceTimeReservationTable;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.auth.Identity;
import com.sun.sgs.kernel.TransactionScheduler;
import com.sun.sgs.test.util.SgsTestNode;
import com.sun.sgs.test.util.TestAbstractKernelRunnable;

public class DStarGridDiagSimpleTabledTest {

	private static SgsTestNode serverNode;
	private static TransactionScheduler txnScheduler;
	private static Identity taskOwner;

	private static final String NAME = "DStarGridDiagSimpleTabledTest";
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		Properties p = SgsTestNode.getDefaultProperties(NAME, null, SgsTestNode.DummyAppListener.class);
        
		p.setProperty("com.sun.sgs.txn.timeout", "4294967"); // for debugging
		
        serverNode = new SgsTestNode(NAME, null, p);
        
        txnScheduler = serverNode.getSystemRegistry().
                getComponent(TransactionScheduler.class);
        taskOwner = serverNode.getProxy().getCurrentOwner();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Test
	public void testPlan() throws Exception {
		txnScheduler.runTask(
				new TestAbstractKernelRunnable() {
				public void run() throws Exception {
					DataManager dataManager = AppContext.getDataManager();
					SpaceTimeReservationTable table = new SpaceTimeReservationTable();
					DStarGridDiagSimpleTabled pathfinder = new DStarGridDiagSimpleTabled(new GridCell(0,0), new GridCell(0,10), dataManager.createReference(table)); 
					//table.addWatcher(dataManager.createReference(pathfinder));
					
					List<GridCell> path = pathfinder.plan();
					//print(path);
					
					assertTrue(path.size() == 11);
					
					//System.out.println(pathfinder.getInnerDatastructures());
					
					ServerShip blocker = new ServerShip(0,0,0,0,0, 0);
					table.reserve(new GridCell(0,1), 0, Long.MAX_VALUE, dataManager.createReference(blocker));
					table.reserve(new GridCell(1,1), 0, Long.MAX_VALUE, dataManager.createReference(blocker));
					table.reserve(new GridCell(-1,1), 0, Long.MAX_VALUE, dataManager.createReference(blocker));
					
					//System.out.println(pathfinder.getInnerDatastructures());
					
					path = pathfinder.plan();
					//print(path);
					assertTrue(path.size() == 12);
				}
				}, taskOwner);
	}

	private void print(List <GridCell> path)
	{
		for (GridCell i : path)
		{
			System.out.print(i + " ");
		}
		System.out.println("");
	}
}
